package com.yanfan.modbus.frame;

import com.yanfan.modbus.ModbusUtils;
import com.yanfan.modbus.code.FunctionCode;
import com.yanfan.modbus.exception.ModbusTransportException;
import com.yanfan.modbus.frame.abs.ModbusRequest;
import io.netty.buffer.ByteBuf;


public class WriteRegisterRequest extends ModbusRequest {
    private int writeOffset;
    private int writeValue;


    public WriteRegisterRequest(int slaveId, int writeOffset, int writeValue) throws ModbusTransportException {
        super(slaveId);
        this.writeOffset = writeOffset;
        this.writeValue = writeValue;
    }


    public WriteRegisterRequest(int slaveId) throws ModbusTransportException {
        super(slaveId);
    }

    @Override
    public void validate() throws ModbusTransportException {
        ModbusUtils.validateOffset(writeOffset);
    }

    @Override
    protected void writeRequest(ByteBuf queue) {
        queue.writeShort(writeOffset);
        queue.writeShort(writeValue);
    }


    @Override
    public byte getFunctionCode() {
        return FunctionCode.WRITE_REGISTER;
    }


    @Override
    protected void readRequest(ByteBuf queue) {
        writeOffset = queue.readUnsignedShort();
        writeValue = queue.readUnsignedShort();
    }
}
